﻿using B.S.BasicData.Api.Write.Application.Command.GridPerson;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Write.Application.Handler.GridPerson
{
    public class DelGridPersonHandler : IRequestHandler<DelGridPersonCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<LogModel> logRepo;
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly ILogger<DelGridPersonHandler> logger;

        public DelGridPersonHandler(IBaseRepository<LogModel> logRepo,IBaseRepository<AccountModel> accountRepo,ILogger<DelGridPersonHandler> logger)
        {
            this.logRepo = logRepo;
            this.accountRepo = accountRepo;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(DelGridPersonCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            //根据id查找要删除的网格人员
            var account =await accountRepo.GetModel(request.Id);

            if (account == null) {//如果没有找到,就结束操作返回响应包装类对象.并且记录日志
                logger.LogError("未找到要删除的网格人员:"+request.Id);
                res.Code = ApiEnum.Error;
                res.Msg = "未找到要删除的网格人员:" + request.Id;
                return res;
            }
            //查到之后,把网格人员的isdeleted改为true
            account.IsDeleted = true;

            //调用仓储的update方法,持久化(保存)到数据库
            int r = await accountRepo.UpdateAsync(account);
            //记录一下日志   //构建日志model对象
            var logModel = new LogModel()
            {
                Id = YitIdHelper.NextId(),//崭新的id
                LogDes = $"正在删除新的网格人员:{account.RealName}",
                Creator = request.Creator,
                CreateTime = DateTime.Now
            };

            logRepo.CreateAsync(logModel);
            //返回响应包装类

            if (r > 0)
            {
                res.Code = ApiEnum.Success;
                res.Data = r;
                res.Msg = "删除网格人员成功.";
            }
            else
            {
                res.Code = ApiEnum.Failed;
                res.Data = 0;
                res.Msg = "删除网格人员失败.";
            }

            return res;
        }
    }
}
